from flask import Blueprint, request, jsonify
from datetime import datetime
import pytz
from database import db
from models import Device, DeviceData

device_data_bp = Blueprint('device_data', __name__)

@device_data_bp.route('/', methods=['POST'])
def receive_device_data():
    """
    Endpoint for devices to send their data to the dashboard.
    Devices will periodically send data to this endpoint.
    """
    data = request.json

    if not data:
        return jsonify({'error': 'No data provided'}), 400

    # Check if device exists, create if not
    device = Device.query.filter_by(device_id=data.get('device_id')).first()

    if not device:
        device = Device(
            device_id=data.get('device_id'),
            name=data.get('name', f"Device {data.get('device_id')}"),
            type=data.get('type', 'unknown'),
            location=data.get('location', 'unknown')
        )
        db.session.add(device)
        db.session.commit()

    # Update device status
    device.status = data.get('status', 'online')
    device.last_update = datetime.utcnow()

    # Create new device data entry
    device_data = DeviceData(
        device_id=device.device_id,
        operator=data.get('operator'),
        shift=data.get('shift'),
        average_speed=data.get('average_speed'),
        shift_length=data.get('shift_length')
    )

    db.session.add(device_data)
    db.session.commit()

    return jsonify({'message': 'Data received successfully', 'device_id': device.id}), 201

@device_data_bp.route('/', methods=['GET'])
def get_device_data():
    """Get data for all devices or filter by device_id."""
    device_id = request.args.get('device_id')
    limit = request.args.get('limit', 100, type=int)

    query = DeviceData.query

    if device_id:
        device = Device.query.filter_by(device_id=device_id).first()
        if not device:
            return jsonify({'error': 'Device not found'}), 404
        query = query.filter_by(device_id=device_id)

    data = query.order_by(DeviceData.timestamp.desc()).limit(limit).all()

    return jsonify({
        'data': [item.to_dict() for item in data]
    }), 200

@device_data_bp.route('/devices', methods=['GET'])
def get_devices():
    """Get a list of all devices."""
    devices = Device.query.all()

    return jsonify({
        'devices': [device.to_dict() for device in devices]
    }), 200

@device_data_bp.route('/devices/<device_id>', methods=['GET'])
def get_device(device_id):
    """Get details for a specific device."""
    device = Device.query.filter_by(device_id=device_id).first()

    if not device:
        return jsonify({'error': 'Device not found'}), 404

    return jsonify(device.to_dict()), 200

@device_data_bp.route('/devices', methods=['POST'])
def create_device():
    """Create a new device."""
    print("Received request to create device")
    data = request.json
    print(f"Request data: {data}")

    if not data:
        print("No data provided")
        return jsonify({'error': 'No data provided'}), 400

    # Check if required fields are present
    if not data.get('device_id') or not data.get('name') or not data.get('type') or not data.get('location'):
        return jsonify({'error': 'Missing required fields'}), 400

    # Check if device with this ID already exists
    existing_device = Device.query.filter_by(device_id=data.get('device_id')).first()
    if existing_device:
        return jsonify({'error': 'Device with this ID already exists'}), 409

    # Create new device
    device = Device(
        device_id=data.get('device_id'),
        name=data.get('name'),
        type=data.get('type'),
        location=data.get('location'),
        status='offline',  # Default status
        last_update=datetime.utcnow()
    )

    db.session.add(device)
    db.session.commit()

    return jsonify({
        'message': 'Device created successfully',
        'device': device.to_dict()
    }), 201

@device_data_bp.route('/devices/<device_id>', methods=['PUT'])
def update_device(device_id):
    """Update an existing device."""
    data = request.json

    if not data:
        return jsonify({'error': 'No data provided'}), 400

    # Find the device
    device = Device.query.filter_by(device_id=device_id).first()
    if not device:
        return jsonify({'error': 'Device not found'}), 404

    # Update device fields
    if 'name' in data:
        device.name = data['name']
    if 'type' in data:
        device.type = data['type']
    if 'location' in data:
        device.location = data['location']

    device.last_update = datetime.utcnow()

    db.session.commit()

    return jsonify({
        'message': 'Device updated successfully',
        'device': device.to_dict()
    }), 200
